
import React, { useState, useEffect } from 'react';
import { useLocation, Link, useNavigate } from 'react-router';
import { Layout, Breadcrumb, Dropdown } from 'antd';
const { Header } = Layout;
import './index.scss';
import LayoutStore from '../../../store/LayoutStore/index';
import useLoginStore from '../../../store/LoginStore/index';
import router from '../../../router/index';
import { DropdownItems } from './index';

const LayoutHeader: React.FC = (props: any) => {

    const collapsed = LayoutStore((state) => state.collapsed); // 折叠状态
    const user_info = useLoginStore((state) => state.user_info); // 用户信息
    const { setCollapsed } = LayoutStore(); // 设置折叠状态
    const { setToken } = useLoginStore(); // 获取store登录信息
    const { routes } = router; // 获取路由配置
    const navigate = useNavigate(); // 路由
    const [breadcrumbNamMap, setBreadcrumbNamMap] = useState<Record<string, string>>({});
    const location = useLocation();
    const pathSnippet = location.pathname.split("/").filter((i) => i);


    useEffect(() => {
        // 遍历 router 配置，生成路径与标题映射
        const generateMap = (routes: any[], parentPath = "", result: Record<string, string> = {}) => {
            routes.forEach((route) => {
                const fullPath = route.path.startsWith("/")
                    ? route.path
                    : `${parentPath}/${route.path}`.replace(/\/+/g, "/");

                if (route.meta?.title) {
                    result[fullPath] = route.meta.title;
                }

                if (route.children) {
                    generateMap(route.children, fullPath, result);
                }
            });
            return result;
        };

        const map = generateMap(routes);
        setBreadcrumbNamMap(map);
    }, []);

    const extraBreadcrumbItems = pathSnippet.map((_, idx) => {
        const url = `/${pathSnippet.slice(0, idx + 1).join("/")}`;
        return {
            title: breadcrumbNamMap[url] ? <Link to={url}>{breadcrumbNamMap[url]}</Link> : url,
            key: url,
        };
    });

    // 改变折叠状态
    const changeCollapsed = () => {
        setCollapsed(!collapsed);
    };

    // 退出登录
    const changeDropdown = (e: any) => {
        const key = e.key;
        if (key === '1') {
            setToken('');
            navigate('/login', { replace: true });
        }
    }

    return (
        <div className='layout-header'>
            <Header style={{ padding: 0, background: '#fff' }}>
                <div className='layout-header-content'>
                    <div className='layout-header-l'>
                        <i className={`iconfont ${collapsed ? 'icon-zhankai' : 'icon-shousuo'}`} onClick={() => changeCollapsed()} />
                        <Breadcrumb items={extraBreadcrumbItems} />
                    </div>
                    <Dropdown menu={{ items: DropdownItems, selectable: true, onClick: (e) => changeDropdown(e) }}>
                        <div className='layout-header-r'>
                            <img className='layout-header-r-img' src={user_info?.avatar} alt="" />
                            <span className='layout-header-r-name'>{user_info?.realname}</span>
                        </div>
                    </Dropdown>
                </div>
            </Header >
        </div >
    );
}

export default LayoutHeader;